<!-- 学社 - 课程 - 认领/选择课程 -->
<template>
  <view class="pb-20">
    <z-paging-list ref="list" v-model="state.list" :safe-area-inset-bottom="false" @loadData="loadData"
      :hide-empty-view="state.fromType == 'course'" :loading-more-enabled="state.fromType == 'work'"
      :refresher-enabled="state.fromType == 'work'">
      <template #top>
        <z-navbar :title="state.fromType == 'course' ? '认领课程' : '添加课程'" :border-bottom="true"></z-navbar>
        <view class="px-4 py-2">
          <u-search class="flex-1" shape="square" disabled :show-action="false" height="72" bg-color="#f6f6f6"
            :input-style="searchInputStyle" placeholder-color="#999" placeholder="搜索课程"
            @click="navigate(`/package_society/pages/search/index?type=course&club_id=${state.club_id}`, true)"/>
        </view>

        <u-tabs bg-color="none" name="category_name" :is-scorll="false" :list="state.categoryList" bar-height="6"
          bar-width="44" active-color="#333" inactive-color="#999" font-size="32" :bar-style="barStyle"
          v-model="state.current" @change="onTabChange"></u-tabs>
      </template>
      <template v-if="state.list.length > 0">
        <view v-for="(item, index) in state.list" :key="index" class="p-4 item">
          <u-checkbox :modelValue="isChecked(item)" shape="circle" active-color="#F4AF22"
            @change="checkboxChange($event, item)" />
          <u-image class="mr-2" width="240" height="160" border-radius="12" :src="item.cover_image"></u-image>
          <view class="flex-1 flex flex-col justify-between h-160 text-single">
            <view class="c-#333 text-28 font-bold text-single">{{ item.class_name }}</view>
            <view>
              <view class="c-#B5B5B5 text-24 text-single mb-1">{{ item.desc }}</view>
              <view class="flex">
                <view class="flex-1 flex items-center text-single">
                  <u-image width="32" height="32" shape="circle" :src="item.teacher_image" />
                  <view class="c-#999 text-26 text-single ml-1">{{ item.teacher_name }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>
      <template v-if="state.fromType == 'course' && state.list.length == 0">
        <view class="pt-20">
          <z-empty imgWidth="228" imgHeight="228" descText="暂无数据" />
        </view>
      </template>
      <template #bottom>
        <view class="h-150 bg-white">
          <u-line class="w-full" color="#eee" :hair-line="false" />
          <view class="btn-submit" @click="onSubmit">确认添加（{{ selectNum }}）</view>
        </view>
      </template>
    </z-paging-list>
  </view>
</template>

<script setup>
import { navigate } from "@/common/util/uni";
import { refreshPrePage } from '@/common/util/util'
import { getCurriculumClaimList, postCurriculumClaim, getSocietyWorkClaimList } from '@/common/http/module/society.js'
import { getOnlineCourseCategoryList } from '@/common/http/module/square.js'

const list = ref();
const state = reactive({
  club_id: '', // 学社id
  categoryList: [], // 课程分类
  list: [], // 课程列表
  category_id: '', // 分类id
  fromType: '', // 学社-课程-course / 学社-学习成长-work
  course_ids: [], // 回显课程集合
  checkedList: [] // 选中课程
})

const barStyle = {
  // color
  backgroundColor: '#F4AF22'
}

const selectNum = computed(() => state.checkedList.length)
// 是否已选中
function isChecked(course) {
  const courseIds = state.checkedList.map(v => v.id)
  return courseIds.includes(course.id) ? true : false
}

// tab切换
function onTabChange(i) {
  state.category_id = state.categoryList[i].id
  if (state.fromType == 'course') {
    loadData()
  } else {
    refresh()
  }
}

// 监听checkbox
function checkboxChange(e, course) {
  // 选中添加 未选中移除
  const isInclude = state.checkedList.some(v => v.id == course.id)
  if (!isInclude) {
    state.checkedList.push(course)
  } else {
    state.checkedList = state.checkedList.filter(v => v.id != course.id)
  }
}

function refresh() {
  list.value.onRefresh()
}

// 添加
function onSubmit() {
  if (state.fromType == 'course') {
    const courseIds = state.checkedList.map(v => v.id)
    postCurriculumClaim({
      club_id: state.club_id,
      class_id: courseIds.join(',')
    }).then(() => {
      // refreshPrePage('refresh')
      navigate(`/package_society/pages/society/index?tabId=3&club_id=${state.club_id}`)
    })
  } else {
    refreshPrePage('onAcceptCourse', state.checkedList)
    setTimeout(() => {
      uni.navigateBack()
    }, 600);
  }
}

async function loadCategory() {
  const { data } = await getOnlineCourseCategoryList()
  state.category_id = data && data[0].id
  state.categoryList = data
  if (state.fromType == 'course') {
    loadData()
  } else {
    refresh()
  }
}

function loadData(page) {
  // 学习成长是已认领课程
  const requestMethod = state.fromType == 'course' ? getCurriculumClaimList : getSocietyWorkClaimList
  requestMethod({ club_id: state.club_id, category_id: state.category_id, name: '', page } ).then(res => {
    if (state.fromType == 'course') {
      state.list = res.data?.data
    } else {
      list.value.onLoadResult(res.data?.data || [])
    }
    state.list.forEach(v => {
      state.course_ids.forEach(c => {
        if (c == v.id) {
          state.checkedList.push(v)
        }
      })
    })
  })
}

onLoad(options => {
  state.club_id = options.club_id
  state.fromType = options.type
  // 初始化选中回显
  if (options.course_ids) {
    state.course_ids = options.course_ids.split(',')
  }
  loadCategory()
  loadData
})
</script>

<style lang="scss" scoped>
.item {
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid #F6F6F6;
}
</style>
